﻿using System.Configuration;

namespace CodeSandbox.Configuration
{
    public class MappingCollection : ConfigurationElementCollection
    {
        public MappingCollection()
        {
            MappingElement mapping = (MappingElement) CreateNewElement();
            if (! string.IsNullOrEmpty(mapping.Destination)) Add(mapping);
        }
        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.BasicMap;
            }
        }
        protected override ConfigurationElement CreateNewElement()
        {
            return new MappingElement();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MappingElement)element).Destination;
        }

        public MappingElement this[int index]
        {
            get
            {
                return (MappingElement)BaseGet(index);
            }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public new MappingElement this[string name]
        {
            get
            {
                return (MappingElement)BaseGet(name);
            }
        }

        public int IndexOf(MappingElement details)
        {
            return BaseIndexOf(details);
        }

        public void Add(MappingElement details)
        {
            BaseAdd(details);
        }

        protected override void BaseAdd(ConfigurationElement element)
        {
            BaseAdd(element, false);
        }

        public void Remove(MappingElement details)
        {
            if (BaseIndexOf(details) >= 0)
                BaseRemove(details.Destination);
        }

        public void RemoveAt(int index)
        {
            BaseRemoveAt(index);
        }

        public void Remove(string name)
        {
            BaseRemove(name);
        }

        public void Clear()
        {
            BaseClear();
        }

        protected override string ElementName
        {
            get { return "mapping"; }
        }
    }
}
